const Koa = require('koa')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const Router = require('koa-router')

const app = new Koa()

const bodyParser = require('koa-bodyparser')
app.use(bodyParser());

const cors = require('koa2-cors')
app.use(cors())

let user = require('./appApi/User')
//装载所有子路由
let router = new Router();
router.use('/user',user.routes())

let article = require('./appApi/Article')
router.use('/admin',article.routes())

let category = require('./appApi/Category')
router.use('/admin',category.routes())

//加载路由中间件
app.use(router.routes())
app.use(router.allowedMethods())

const mongoose = require('mongoose')
const {connect , initSchemas} = require('./database/init.js')

;(async()=>{
  await connect()
  initSchemas()
  // const User = mongoose.model('User')
  // //插入数据
  // let oneUser = new User({userName:'zhuyong7',password:'123456'})

  // oneUser.save().then(()=>{
  //   console.log('插入成功')
  // })

  // let users = await User.find({}).exec()
  // const wzlb = mongoose.model('Article')
  // // console.log(users)
  // let wzlbList = await wzlb.find({}).exec()
  // console.log(wzlbList)
})()



// Import and Set Nuxt.js options
let config = require('../nuxt.config.js')
config.dev = !(app.env === 'production')

async function start() {
  // Instantiate nuxt.js
  const nuxt = new Nuxt(config)
  
  const {
    host = process.env.HOST || '127.0.0.1',
    port = process.env.PORT || 3000
  } = nuxt.options.server

  // Build in development
  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  }

  app.use(ctx => {
    ctx.status = 200
    ctx.respond = false // Bypass Koa's built-in response handling
    ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
    nuxt.render(ctx.req, ctx.res)
  })

  app.listen(port, host)
  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true
  })
}

start()
